
/**
 * @author LC
 *
 */
package com.cyys.modules.core.exception;


import com.cyys.common.ql.AjaxJson;
import com.cyys.common.utils.http.HttpKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
	private static Logger log = LoggerFactory.getLogger(ExceptionHandler.class);
	private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s Detail: %s";

	HttpServletRequest request;
	//运行时异常
	@ExceptionHandler(RuntimeException.class)
	public AjaxJson runtimeExceptionHandler(RuntimeException ex) {

		return resultFormat(1, ex);
	}

	//空指针异常
	@ExceptionHandler(NullPointerException.class)
	public AjaxJson nullPointerExceptionHandler(NullPointerException ex) {
		System.err.println("NullPointerException:");
		return resultFormat(2, ex);
	}

	//类型转换异常
	@ExceptionHandler(ClassCastException.class)
	public AjaxJson classCastExceptionHandler(ClassCastException ex) {
		return resultFormat(3, ex);
	}

	//IO异常
	@ExceptionHandler(IOException.class)
	public AjaxJson iOExceptionHandler(IOException ex) {
		return resultFormat(4, ex);
	}

	//未知方法异常
	@ExceptionHandler(NoSuchMethodException.class)
	public AjaxJson noSuchMethodExceptionHandler(NoSuchMethodException ex) {
		return resultFormat(5, ex);
	}

	//数组越界异常
	@ExceptionHandler(IndexOutOfBoundsException.class)
	public AjaxJson indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
		return resultFormat(6, ex);
	}

	//400错误
	@ExceptionHandler({HttpMessageNotReadableException.class})
	public AjaxJson requestNotReadable(HttpMessageNotReadableException ex) {
		System.out.println("400..requestNotReadable");
		return resultFormat(7, ex);
	}

	//400错误
	@ExceptionHandler({TypeMismatchException.class})
	public AjaxJson requestTypeMismatch(TypeMismatchException ex) {
		System.out.println("400..TypeMismatchException");
		return resultFormat(8, ex);
	}

	//400错误
	@ExceptionHandler({MissingServletRequestParameterException.class})
	public AjaxJson requestMissingServletRequest(MissingServletRequestParameterException ex) {
		System.out.println("400..MissingServletRequest");
		return resultFormat(9, ex);
	}

	//405错误
	@ExceptionHandler({HttpRequestMethodNotSupportedException.class})
	public AjaxJson request405(HttpRequestMethodNotSupportedException ex) {
		return resultFormat(10, ex);
	}

	//406错误
	@ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
	public AjaxJson request406(HttpMediaTypeNotAcceptableException ex) {
		System.out.println("406...");
		return resultFormat(11, ex);
	}

	//500错误
	@ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
	public AjaxJson server500(RuntimeException ex) {
		System.out.println("500...");
		return resultFormat(12, ex);
	}

	//栈溢出
	@ExceptionHandler({StackOverflowError.class})
	public AjaxJson requestStackOverflow(StackOverflowError ex) {
		return resultFormat(13, ex);
	}

	//除数不能为0
	@ExceptionHandler({ArithmeticException.class})
	public AjaxJson arithmeticException(ArithmeticException ex) {
		return resultFormat(14, ex);
	}


	//图片上传大小超出限制
	@ExceptionHandler({MaxUploadSizeExceededException.class})
	public AjaxJson maxUploadSizeExceededException(ArithmeticException ex) {
		return resultFormat(15, ex);
	}

	//其他错误
	@ExceptionHandler({Exception.class})
	public AjaxJson exception(Exception ex) {
		return resultFormat(16, ex);
	}

	private <T extends Throwable> AjaxJson resultFormat(Integer code, T ex) {
		AjaxJson aj = new AjaxJson();
		aj.setErrorCode(code.toString());
		aj.setMsg(ex.getClass().getSimpleName() + "：" + ex.getMessage());
		aj.setSuccess(false);
		aj.put("excetion", ex.getMessage());
		log.error("【抛出异常】--异常路径为：" +  HttpKit.getRequest().getServletPath() + "\n【异常信息】--" +  ex);
		log.error(ex.getStackTrace().toString());
		ex.printStackTrace();
		return aj;
	}
//
//	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
//            Object handler, Exception ex ) {
//    	 ModelAndView mv = new ModelAndView();
//         /*  使用response返回    */
//         response.setStatus(HttpStatus.OK.value()); //设置状态码
//         response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
//         response.setCharacterEncoding("UTF-8"); //避免乱码
//         response.setHeader("Cache-Control", "no-cache, must-revalidate");
//         log.error("【抛出异常】--异常路径为：" +  request.getServletPath() + "\n【异常信息】--" +  ex);
//         log.error(ex.getStackTrace().toString());
//         if(ex instanceof MaxUploadSizeExceededException){
//         	MaxUploadSizeExceededException me = (MaxUploadSizeExceededException)ex;
//         	try {
//				response.getWriter().write("{\"success\":false,\"msg\":\"图片上传大小超出限制：" + me.getMaxUploadSize() + "\"}");
//			} catch (IOException e) {
//				log.error("客户端断开连接" + e.getMessage());
//			}
//         }else if(ex instanceof IOException){
//        	 if(ex.getMessage().equals("Broken pipe")){
//        		 try {
//					response.getWriter().write("{\"success\":false,\"msg\":\"客户端断开连接\"}");
//				} catch (IOException e) {
//					log.error("客户端断开连接" + e.getMessage());
//				}
//          	}else{
//          		 try {
//     				response.getWriter().write("{\"success\":false,\"msg\":\"" + ex.getMessage() + "\"}");
//     			} catch (IOException e) {
//     				log.error("客户端断开连接" + e.getMessage());
//     			}
//          	}
//         }else{
//        	 try {
//				response.getWriter().write("{\"success\":false,\"msg\":\"" + ex.getMessage() + "\"}");
//			} catch (IOException e) {
//				log.error("客户端断开连接" + e.getMessage());
//			}
//         }
//         return mv;
//    }
}